package com.dingding.es.operation;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.Result;
import co.elastic.clients.elasticsearch._types.query_dsl.MatchQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.bulk.BulkOperation;
import co.elastic.clients.elasticsearch.core.bulk.CreateOperation;
import co.elastic.clients.elasticsearch.core.search.HitsMetadata;
import co.elastic.clients.elasticsearch.indices.*;
import com.dingding.es.model.User;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @author liugongding
 * @description:
 * @date 2023/4/10 11:40 PM
 */

@Service
public class Operation {

    @Autowired
    private ElasticsearchClient client;

    public void createIndexRequest() throws Exception{
        //获取索引客户端对象
        ElasticsearchIndicesClient indices = client.indices();
        boolean flag = indices.exists(req -> {
            req.index("java_test_doc");
            return req;
        }).value();
        if (flag) {
            System.out.println("索引test_doc已存在");
        } else {
            List<String> list = Lists.newArrayList("1");
            CreateIndexResponse test_doc = indices.create(req -> {
                req.index("java_test_doc");
                return req;
            });
            System.out.println(test_doc);
        }
    }

    public void getIndexRequest() throws IOException {
        ElasticsearchIndicesClient indices = client.indices();
        GetIndexRequest indexRequest = new GetIndexRequest.Builder().index("test_doc").build();
        GetIndexResponse getIndexResponse = indices.get(indexRequest);
        System.out.println(getIndexResponse);
    }

    public void deleteIndexRequest() throws IOException {
        ElasticsearchIndicesClient indices = client.indices();
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest.Builder().index("test_doc").build();
        DeleteIndexResponse delete = indices.delete(deleteIndexRequest);
        System.out.println(delete);
    }

    //文档操作
    public String createDocument() throws IOException {
        CreateRequest<User> build = new CreateRequest.Builder<User>()
                .index("index_user")
                .id("1001")
                .document(new User(1,"dingding",26))
                .build();
        CreateResponse createResponse = client.create(build);
        return createResponse.toString();
    }

    //批量新增
    public String createDocumentBatch() throws IOException {
        List<BulkOperation> opts = Lists.newArrayList();
        for (int i=0; i<5; i++) {
            CreateOperation<User> build = new CreateOperation.Builder<User>()
                    .index("index_user")
                    .id("1002" + i)
                    .document(new User(i, "dingding", 26 + i))
                    .build();
            BulkOperation operation = new BulkOperation.Builder().create(build).build();
            opts.add(operation);
        }
        BulkRequest bulkRequest = new BulkRequest.Builder().operations(opts).build();
        BulkResponse bulk = client.bulk(bulkRequest);
        return bulk.toString();
    }

    //删除文档数据
    public String deleteDocument() throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest.Builder()
                .index("index_user")
                .id("10020")
                .build();
        DeleteResponse delete = client.delete(deleteRequest);
        return delete.toString();
    }

    //public String getDocument() throws IO
    public String createDocumentLambda() throws IOException {
        Result result = client.create(req ->
                req.index("index_user")
                        .id("10060")
                        .document(new User(10, "dingding", 26))

        ).result();
        return result.toString();
    }

    public String createDocumentBatchLambda() throws IOException {
        List<User> list = Lists.newArrayList();
        for (int i=0; i<5; i++) {
            list.add(new User(121+i, "dingding"+i, 26+i));
        }
        BulkResponse bulkResponse = client.bulk(req -> {
            list.forEach(user -> {
                req.operations(b -> b.create(
                        d -> d.index("index_user")
                                .id(user.getId().toString())
                                .document(user)
                ));
            });
            return req;
        });
        return bulkResponse.toString();
    }

    public String deleteDocumentLambda() throws IOException {
        DeleteResponse deleteResponse = client.delete(req -> req.index("index_user").id("1001"));
        return deleteResponse.toString();
    }

    public void queryDocument() throws IOException {
        MatchQuery matchQuery = new MatchQuery.Builder()
                .field("age").query(30)
                .build();

        Query query = new Query.Builder().match(matchQuery).build();
        SearchRequest request = new SearchRequest.Builder()
                .query(query)
                .build();
        SearchResponse<Object> search = client.search(request, Object.class);
        System.out.println(search);
    }

    public void queryDocumentLambda() throws IOException {
        SearchResponse<Object> search = client.search(req ->
                req.query(q ->
                        q.match(t ->
                                t.field("name").query("dingding")
                        )
                ), Object.class);
        HitsMetadata<Object> hits = search.hits();
        System.out.println(hits);
    }

}
